package cn.e3.sso.service.impl;

import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import cn.e3.jedis.JedisClient;
import cn.e3.mapper.TbUserMapper;
import cn.e3.pojo.TbUser;
import cn.e3.pojo.TbUserExample;
import cn.e3.pojo.TbUserExample.Criteria;
import cn.e3.sso.service.LoginService;
import cn.e3.utils.E3Result;
import cn.e3.utils.JsonUtils;
@Service
public class LoginServiceImpl implements LoginService{
	@Autowired
	private JedisClient jedisClient;
	@Autowired
	private TbUserMapper userMapper;
	@Value("${SESSION_EXPIRE}")
	private Integer session_expire;
	public E3Result login(String username, String password) {
		//判断应户名是否正确·
		TbUserExample example=new TbUserExample();
		Criteria criteria = example.createCriteria();
		criteria.andUsernameEqualTo(username);
		List<TbUser> list = userMapper.selectByExample(example);
		
		//判断查询结果
		if(list==null&&list.size()<0){
			return E3Result.build(400, "用户名错误");
		}
		TbUser user=list.get(0);
		//判断密码是否一致
		if(!DigestUtils.md5DigestAsHex(password.getBytes()).equals(list.get(0).getPassword())){
			return E3Result.build(400,"密码错误");
		}
		//校验成功，生产token
		String token = UUID.randomUUID().toString();
		//为了安全，将用户密码排除在json外
		user.setPassword(null);
		//将token和用户信息放入redis中
		jedisClient.set("SessionId"+token, JsonUtils.objectToJson(user));
		//设置redis的过期时间
		jedisClient.expire("SessionId"+token, session_expire);
		return E3Result.ok(token);	}
	
}
